#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

//gcc -D_GNU_SOURCE 5.5.c 


void checkFd(int fd){
    off_t off;
    off = lseek(fd, 0, SEEK_CUR);
    if(off == -1){
        printf("Error lseek fd %d %s\n", fd, strerror(errno));
        exit(EXIT_FAILURE);
    }  
    printf("Ofset %d = %ld\n", fd, off);
}


void checkFlags(int fd){
    int flags, accessMode;
    flags = fcntl(fd, F_GETFL);
    if(flags == -1){
        printf("Error fcntl fd %d %s\n", flags, strerror(errno));
        exit(EXIT_FAILURE);
    }
    accessMode = flags & O_ACCMODE;
    printf("fd %d:\n", fd);
    if(accessMode & O_RDONLY)
        printf("O_RDONLY ");
    if(accessMode & O_WRONLY)
        printf("O_WRONLY ");
    if(accessMode & O_RDWR)
        printf("O_RDWR ");

    if(flags & O_RDONLY)
        printf("O_RDONLY ");
    if(flags & O_WRONLY)
        printf("O_WRONLY ");
    if(flags & O_RDWR)
        printf("O_RDWR ");
    if(flags & O_CLOEXEC)
        printf("O_CLOEXEC ");
    if(flags & O_CREAT)
        printf("O_CREAT ");
    if(flags & O_DIRECTORY)
        printf("O_DIRECTORY ");            
    if(flags & O_EXCL)
        printf("O_EXCL ");            
    if(flags & O_LARGEFILE)
        printf("O_LARGEFILE ");
    if(flags & O_NOCTTY)
        printf("O_NOCTTY ");    
    if(flags & O_NOFOLLOW)
        printf("O_NOFOLLOW ");            
    if(flags & O_TRUNC)
        printf("O_TRUNC ");     
    if(flags & O_APPEND)
        printf("O_APPEND ");     
    if(flags & O_ASYNC)
        printf("O_ASYNC ");         
    if(flags & O_DIRECT)
        printf("O_DIRECT ");    
    if(flags & O_DSYNC)
        printf("O_DSYNC ");   
    if(flags & O_NOATIME)
        printf("O_NOATIME ");         
    if(flags & O_NONBLOCK)
        printf("O_NONBLOCK ");     
    if(flags & O_SYNC)
        printf("O_SYNC ");   
    if(flags & O_CREAT)
        printf("O_CREAT ");          
    puts("");                                                                      
}

int main(){
    int fd1, fd2;
    char *pathTOFilePtr = "file56.txt";

    fd1 = open(pathTOFilePtr, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IROTH);
    if(fd1 == -1){
        printf("Error open with create file %s %s\n", pathTOFilePtr, strerror(errno));
        exit(EXIT_FAILURE);
    }
    fd2 = open(pathTOFilePtr, O_RDWR | O_APPEND | O_NONBLOCK);
    if(fd2 == -1){
        printf("Error open file %s %s\n", pathTOFilePtr, strerror(errno));
        exit(EXIT_FAILURE);
    }   

    checkFd(fd1);
    checkFd(fd2);
    checkFlags(fd1);
    checkFlags(fd2);

    if (close(fd1) == -1){
        printf("Error close file1 %s %s\n", pathTOFilePtr, strerror(errno));
        exit(EXIT_FAILURE);
    }
    if (close(fd2) == -1){
        printf("Error close file2 %s %s\n", pathTOFilePtr, strerror(errno));
        exit(EXIT_FAILURE);
    }    
    exit(EXIT_SUCCESS);
}